//
//  JBMAGroup.m
//  MediaAssets
//
//  Created by Yongbin Zhang on 12/25/13.
//  Copyright (c) 2013 JustBen. All rights reserved.
//

#import "JBMAGroup.h"


@interface JBMAGroup ()

@property (nonatomic, retain) ALAssetsLibrary *assetsLibrary;

+ (ALAssetsLibrary *)defaultAssetsLibrary;

@end


@implementation JBMAGroup


#pragma mark - ALAssetsLibrary

+ (ALAssetsLibrary *)defaultAssetsLibrary
{
    static dispatch_once_t onceTokenForAssetsLibrary;
    static ALAssetsLibrary *staticAssetsLibrary = nil;
    dispatch_once(&onceTokenForAssetsLibrary, ^{
        staticAssetsLibrary = [[ALAssetsLibrary alloc] init];
    });
    return staticAssetsLibrary;
}


//  根据ALAssetsGroupType获取相应的ALAssetsGroup列表
+ (void)loadGroupsWithTypes:(ALAssetsGroupType)types assetsFilter:(ALAssetsFilter *)assetsFilter success:(void (^)(NSArray *groups))success failure:(void (^)(NSError *error))failure
{
    NSMutableArray *groups = [[NSMutableArray alloc] init];
    ALAssetsLibraryGroupsEnumerationResultsBlock resultsBlock = ^(ALAssetsGroup *group, BOOL *stop) {
        if (group)
        {
            if (group.numberOfAssets > 0)
            {
                if (assetsFilter) {
                    [group setAssetsFilter:assetsFilter];
                }
                
                [groups addObject:group];
            }
        } else {
            if (success) {
                success(groups);
            }
        }
    };
    
    ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
        if (failure) {
            failure(error);
        }
    };
    
    [[self defaultAssetsLibrary] enumerateGroupsWithTypes:types usingBlock:resultsBlock failureBlock:failureBlock];
}

@end
